//
//  CompanyImageView.m
//  AntsExpress
//
//  Created by slccper on 16/1/1.
//  Copyright © 2016年 slccper. All rights reserved.
//

#import "cImageView.h"
#import "clsFileFun.h"
#import "clsOtherFun.h"

#define kTimeoutInterval_Image 60.0

@interface cImageView ()
- (void)initData;
- (void)showImage:(UIImage *)image;
@end


@implementation cImageView

@synthesize activityView;
@synthesize delegate;
@synthesize serverDirectory;
@synthesize localDirectory;
@synthesize saveName;
@synthesize noNetImage;
@synthesize errorImage;
@synthesize noImage;
@synthesize guid;
@synthesize IsDisableImageAnimation;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        delegate = nil;
        serverDirectory = nil;
        localDirectory = nil;
        noNetImage = nil;
        errorImage = nil;
        noImage = nil;
        guid = nil;
        theConnection = nil;
        webData = nil;
        saveName=nil;
        activityView = [[UIActivityIndicatorView alloc] init];
        [self addSubview:activityView];
        
        [self initData];
        
    }
    return self;
}

- (id)init {
    self = [self initWithFrame:CGRectZero];
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        delegate = nil;
        serverDirectory = nil;
        localDirectory = nil;
        noNetImage = nil;
        errorImage = nil;
        noImage = nil;
        guid = nil;
        theConnection = nil;
        webData = nil;
        saveName=nil;
        activityView = [[UIActivityIndicatorView alloc] init];
        [self addSubview:activityView];
        
        [self initData];
        
    }
    return self;
}

- (void)setFrame:(CGRect)frame {
    super.frame = frame;
    [self initData];
}

- (void)initData {
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;

    if (activityView) {
        if (width <= 0 || height <= 0 ) {
            activityView.color = [UIColor clearColor];
        } else if (width <= 60 || height <=60 ) {
            activityView.center = CGPointMake(width / 2.0, height / 2.0);
            activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
            activityView.color = [UIColor darkGrayColor];
        } else {
            activityView.center = CGPointMake(width / 2.0, height / 2.0);
            activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
            activityView.color = [UIColor darkGrayColor];
        }
    }
}

- (void)showImage:(UIImage *)image {
//    if (IsDisableImageAnimation) {
        self.image = image;
    app.networkActivityIndicatorVisible = NO;
//    }else {
//        self.alpha = 0.0f;
//        self.image = image;
    
//        [UIView beginAnimations:nil context:nil];
//        [UIView setAnimationDuration:0.5];
//        self.alpha = 1.0f;
//        [UIView commitAnimations];
//    }
}

- (void)refreshImage {
    activityView.hidden = NO;
	[activityView startAnimating];
    
    self.image = nil;
    [theConnection cancel];
    theConnection = nil;
    webData = nil;
    if (![saveName isEqualToString:@""]) {
        NSURL *url =[NSURL URLWithString:[clsFileFun getFilePath:serverDirectory :saveName]];
        NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:kTimeoutInterval_Image];
        theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        //如果连接已经建好，则初始化data
        if (theConnection) {
            webData = [[NSMutableData alloc] init];
        }	
    } else {
        [self showImage:noNetImage];
        activityView.hidden = YES;
        [activityView stopAnimating];
	}	
}

- (void)loadImage {
    activityView.hidden = NO;
	[activityView startAnimating];
    
    self.image = nil;
    [theConnection cancel];
    theConnection = nil;
    webData = nil;
    if (![saveName isEqualToString:@""]) {
        NSString *path = [clsFileFun getFilePath:localDirectory :saveName];
        NSData *data = [clsFileFun loadFile:path];
        if(data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                activityView.hidden = YES;
                [activityView stopAnimating];
                [self showImage:image];
                if (delegate && [delegate respondsToSelector:@selector(loadImageSuccess)]) {
                    [delegate loadImageSuccess];
                }
                if (delegate && [delegate respondsToSelector:@selector(loadImageSuccess2:)]) {
                    [delegate loadImageSuccess2:self];
                }

                return;
            }
        }
        
        if([clsOtherFun CheckNetworkStatus:NO]) {
            app = [ UIApplication sharedApplication ];
            app.networkActivityIndicatorVisible = YES;
            NSURL *url =[NSURL URLWithString:[clsFileFun getFilePath:serverDirectory :saveName]];
            NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:kTimeoutInterval_Image];
            theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            //如果连接已经建好，则初始化data
            if (theConnection) {
                webData = [[NSMutableData alloc] init];
            }	
        } else {
            [self showImage:noNetImage];
            activityView.hidden = YES;
            [activityView stopAnimating];
        }
    } else {
        [self showImage:noImage];
		activityView.hidden = YES;
		[activityView stopAnimating];
	}	
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)incrementalData {
    [webData appendData:incrementalData];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSString *path = [clsFileFun getFilePath:localDirectory :saveName];
    NSData *data = [clsFileFun loadFile:path];
    UIImage *image = [UIImage imageWithData:data];
    if (!image) {
        image = errorImage;
    }
    [self showImage:image];
    
    theConnection = nil;
    webData = nil;
    app=nil;
	activityView.hidden = YES;
	[activityView stopAnimating];
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
	UIImage *image = [UIImage imageWithData:webData];
	if (image) {
        [self showImage:image];
		[[NSFileManager defaultManager] createDirectoryAtPath:localDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *path = [clsFileFun getFilePath:localDirectory :saveName];
		[clsFileFun saveFile:path :webData];
        if (delegate && [delegate respondsToSelector:@selector(loadImageSuccess)]) {
            [delegate loadImageSuccess];
        }
        if (delegate && [delegate respondsToSelector:@selector(loadImageSuccess2:)]) {
            [delegate loadImageSuccess2:self];
        }

	} else {
        [self showImage:errorImage];
    }
    
    theConnection = nil;
    webData = nil;
    app=nil;
	activityView.hidden = YES;
    [activityView stopAnimating];
}

- (void)cancel {
    [theConnection cancel];
    theConnection = nil;
    webData = nil;
    app=nil;
    activityView.hidden = YES;
    [activityView stopAnimating];
}

@end
